<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { registerAPI } from '@/apis/user.js';
import { ElMessage } from 'element-plus';

const router = useRouter();
const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  address: ''
});

const isUsernameFocused = ref(false);
const isPasswordFocused = ref(false);
const isConfirmPwdFocused = ref(false);
const isEmailFocused = ref(false);

const isPwdVisible = ref(false);
const isLoading = ref(false);

// 表单Ref（用于校验）
const formRef = ref(null);

// 表单校验规则
const formRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '用户名长度需在3-16位之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的电子邮箱格式', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度需在6-16位之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback(); // 校验通过
        }
      },
      trigger: 'blur'
    }
  ]
});


const togglePwdVisibility = () => { isPwdVisible.value = !isPwdVisible.value; }; // 切换状态

const handleRegister = async () => {
  try {
    await formRef.value.validate();

    isLoading.value = true;
    await registerAPI(registerForm.value);
    ElMessage.success('注册成功！即将跳转到登录页');
    router.push('/user/login');
  } catch (err) {
    throw err;
  } finally {
    isLoading.value = false;
  }
};

</script>

<template>
  <el-form 
    ref="formRef"
    :model="registerForm"
    :rules="formRules"
    label-width="0px" 
    class="register-form-container"
  >
  
      <!-- 注册表单 -->
      <div class="register-form">
        <strong class="register-title">注册</strong> 

        <!-- 用户名输入框 -->
        <el-form-item prop="username" class="form-item">
          <div class="input-box" :class="{ 'focused': isUsernameFocused }">
            <img src="/icon/user-brown.png" alt="用户名图标" class="icon-img-left">
            
            <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名（3-16位）"
              class="input-inner"
              @focus="isUsernameFocused = true"
              @blur="isUsernameFocused = false"
            />
          </div>
        </el-form-item>
        
        <!-- 电子邮箱输入框 -->
        <el-form-item prop="email" class="form-item">
          <div class="input-box" :class="{ 'focused': isEmailFocused }">
              <img src="/icon/email-gray.png" alt="电子邮箱图标" class="icon-img-left">
              
              <el-input
                v-model="registerForm.email"
                placeholder="请输入电子邮箱"
                class="input-inner"
                @focus="isEmailFocused = true"
                @blur="isEmailFocused = false"
              />
          </div>
      </el-form-item>

        <!-- 密码输入框 -->
        <el-form-item prop="password" class="form-item">
          <div class="input-box" :class="{ 'focused': isPasswordFocused }">
              <img src="/icon/password.png" alt="密码图标" class="icon-img-left">
              
              <el-input
                v-model="registerForm.password"
                :type="isPwdVisible ? 'text' : 'password'"
                placeholder="请输入密码（6-16位）"
                class="input-inner"
                @focus="isPasswordFocused = true"
                @blur="isPasswordFocused = false"
              />

              <img 
                :src="isPwdVisible ? '/icon/look.png' :'/icon/unlook.png' " 
                alt="密码显示切换" 
                width="20px"
                height="20px"
                @click="togglePwdVisibility"
                class="icon-img-right"
              >
          </div>
      </el-form-item>

        <!-- 确认密码输入框 -->
        <el-form-item prop="confirmPassword" class="form-item">
          <div class="input-box" :class="{ 'focused': isConfirmPwdFocused }">
              <img src="/icon/password.png" alt="确认密码图标" class="icon-img-left">
              
              <el-input
                v-model="registerForm.confirmPassword"
                :type="isPwdVisible ? 'text' : 'password'"
                placeholder="请确认密码"
                class="input-inner"
                @focus="isConfirmPwdFocused = true"
                @blur="isConfirmPwdFocused = false"
              />

              <img 
                :src="isPwdVisible ? '/icon/look.png' :'/icon/unlook.png' " 
                alt="确认密码显示切换" 
                width="20px"
                height="20px"
                @click="togglePwdVisibility"
                class="icon-img-right"
              >
          </div>
      </el-form-item>

        <!-- 已有账号：跳转登录链接--> 
        <div class="form-link">
            已有账号？
            <a href="/user/login" class="register-link">立即登录</a>
        </div>
      </div>

      <!-- 注册按钮 -->
      <div class="reg-button"> 
          <el-button
            @click="handleRegister"
            :loading="isLoading"
          >
            <span>立即注册</span>
          </el-button>
        </div>
      </el-form>
</template>

<style scoped>
.register-form-container {
  width: 100%;
  max-width: 500px; 
  margin: 0 auto;
}
.register-form {
  margin-top: 14px;
  padding: 0 56px;
}
.register-title {
  font-size: 22px;
  line-height: 31px;
  color: #2B2B2B;
}
.form-item {
  margin-bottom: 0; 
}
.input-box {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-top: 22px;
  width: 100%; 
  height: 52px;
  background: #FAFAFA;
  border-radius: 4px;
  border: 1px solid transparent;
  transition: border-color 0.3s;
}
.icon-img-left {
  width: 20px;
  height: 20px;
  margin-left: 16px;
}
.icon-img-right {
  width: 20px;
  height: 20px;
  margin-right: 16px;
}

/* 链接 */
.form-link {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
.form-link .register-link {
  color: #4077FB;
}

/* 注册按钮 */
.reg-button {
  width: 378px;
  height: 52px;
  line-height: 52px;
  margin: 0 auto;
  margin-top: 55px;
}
.reg-button button{
  width: 100%;
  height: 100%;
  text-align: center;
  background: #4077FB;
  border-radius: 4px;
  color: #FFFFFF;
  font-size: 20px;
}

/* 输入框聚焦样式 */
.input-box.focused {
  border: 1px solid #4077FB;
}

/* 输入框占位符颜色 */
:deep(.input-inner .el-input__inner)::placeholder {
  color: #AAB1BA;
}

/* 清除Element输入框默认样式 */
:deep(.input-inner .el-input__inner) {
  border: none;
  padding: 0;
  background: transparent;
  height: 100%;
}
:deep(.input-inner .el-input__wrapper) {
  box-shadow: none;
  background: transparent;
  padding: 0;
}
:deep(.input-inner .el-input__suffix) {
  display: none;
}
/* 清除Element Plus表单错误状态的边框/样式 */
:deep(.el-form-item.is-error .el-input__wrapper) {
  border: none !important; /* 去掉输入框错误边框 */
  box-shadow: none !important;
}
:deep(.el-form-item.is-error) {
  border: none !important; /* 去掉表单项错误边框 */
}
</style>
